#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    //@ysh's method
    // int candy(vector<int> &ratings)
    // {
    //     int length = ratings.size();
    //     vector<int> candy(length, 1);
    //     int pre = 0;
    //     int cur = 1;
    //     while (cur <= length - 1)
    //     {
    //         if (ratings[pre] < ratings[cur])
    //         {
    //             candy[cur] = candy[pre] + 1;
    //         }
    //         pre++;
    //         cur++;
    //     }
    //     pre = length - 1;
    //     cur = length - 2;
    //     while (cur >= 0)
    //     {
    //         if (ratings[pre] < ratings[cur] && candy[pre] >= candy[cur])
    //         {
    //             candy[cur] = candy[pre] + 1;
    //         }
    //         pre--;
    //         cur--;
    //     }
    //     int sum = accumulate(candy.begin(), candy.end(), 0);
    //     return sum;
    // }

    int candy(vector<int> &ratings)
    {
        int length = ratings.size();
        vector<int> candy(length, 1);
        for (int i = 1; i < length; i++)
        {
            if (ratings[i] > ratings[i - 1])
            {
                candy[i] = candy[i - 1] + 1;
            }
        }
        for (int i = length - 2; i >= 0; i--)
        {
            if (ratings[i] > ratings[i + 1])
            {
                candy[i] = max(candy[i + 1] + 1, candy[i]);
            }
        }
        int sum = accumulate(candy.begin(), candy.end(), 0);
        return sum;
    }
};

int main()
{
    vector<int> rating{1, 2, 3, 3, 2, 1};
    Solution sol;
    cout << sol.candy(rating) << endl;
    return 0;
}